<?php
	include_once 'data.php';
	include_once 'functions.php';

	require_once('application/model/sql/Connection.class.php');
	require_once('application/model/sql/ConnectionFactory.class.php');
	require_once('application/model/sql/ConnectionProperty.class.php');
	require_once('application/model/sql/Transaction.class.php');
	require_once('application/model/sql/QueryExecutor.class.php');	
	require_once('application/model/sql/SqlQuery.class.php');
	require_once('application/model/core/ArrayList.class.php');
	require_once('application/model/dao/DAOFactory.class.php');
	
	require_once 'application/model/dao/UsersDAO.class.php';
	require_once 'application/model/impl/UsersSqliteDAO.class.php';
	require_once 'application/model/impl/ext/UsersSqliteExtDAO.class.php';
	require_once 'application/model/dao/DAOFactory.class.php';
	require_once 'application/model/dto/User.class.php';
	require_once 'lib/LDAPHandler.php';
	
########upgrade hack, may be removed after upgrading to 2.1###########
if(is_file($database_path.'library.sq3')) {
    database_connect($database_path, 'library');
    $result = $dbHandle->query("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='categories'");
    $newtable = $result->fetchColumn();
    $result = null;
    $dbHandle = null;
    if ($newtable == 0) include_once 'migrate.php';
}
########upgrade hack, may be removed after upgrading to 2.1###########

/////////////// LDAP SETTINGS //////////////////////////////
$ldap_active = false; /*activate or not the LDAP login*/
if (!extension_loaded('ldap')) $ldap_active = false;
/////////////// END LDAP SETTINGS //////////////////////////////

///////////////start sign out//////////////////////////////
if (isset($_GET['action']) && $_GET['action'] == 'signout') {

    $clean_files = scandir($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id());
    foreach($clean_files as $clean_file) {
        if(is_file($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id().DIRECTORY_SEPARATOR.$clean_file))
            unlink($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id().DIRECTORY_SEPARATOR.$clean_file);
    }
    rmdir($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id());
    $_SESSION = array();
    session_destroy();
    die('OK');
}
///////////////end sign out////////////////////////////////


///////////////start authentication////////////////////////
if (isset($_POST['form']) && $_POST['form']=='signin' && !empty($_POST['user']) && !empty($_POST['pass']) && !isset($_SESSION['auth'])) {

    $username=$_POST['user'];
    $password=$_POST['pass'];

    database_connect($database_path, 'library');

    $quoted_path = $dbHandle->quote($database_path.'users.sq3');

    $dbHandle->exec("ATTACH DATABASE $quoted_path AS userdatabase");

    $dbHandle->beginTransaction();
	
    $username_quoted = $dbHandle->quote($username);

    /*IS THE USER AN LDAP USER?*/
    if($ldap_active) {
		
        $ldap = new LDAPHandler();
        $user = $ldap->authenticate($username, $password);
		
        /*AUTHENTICATE*/
        if($user != null) {
						
			//$tmp = DAOFactory::getUsersDAO()->queryByUsername(trim($user->getUsername()));			
			$user_tmp = $dbHandle->query("SELECT * FROM userdatabase.users WHERE username = '".$user->getUsername()."' ");
			$user_tmp = $user_tmp->fetchAll();
											
			if(!empty($user_tmp)){
				$user = new User();					
				$user->setUsername($user_tmp[0]['username']);
				$user->setPassword($user_tmp[0]['password']);
				$user->setPermissions($user_tmp[0]['permissions']);
				$user->setId($user_tmp[0]['userID']);								
			}
			
			if($user->getId() != null){
				//EXISTING USER
				$count = $dbHandle->query("SELECT count(*) FROM shelves WHERE userID=".$user->getId()." LIMIT 1");				
				$rows = $count->fetchColumn();
				$count = null;

				if ($rows == 0) {
					$dbHandle->exec("INSERT INTO shelves (fileID,userID) VALUES (".$user->getId().",'')");
					//$dbHandle->exec("INSERT INTO shelves (user,password,files,permissions) VALUES ($username_quoted,'null','','$permissions')");
					//$dbHandle->exec("INSERT INTO desktop (user,project,files,access) VALUES ($username_quoted,'My Project','','')");
				}
				$dbHandle->commit();

			}else{
				//CREATE A NEW USER
				
				///////////////start register new user////////////////////						
				database_connect($database_path, 'library');

				$quoted_path = $dbHandle->quote($database_path.'users.sq3');

				$dbHandle->exec("ATTACH DATABASE $quoted_path AS userdatabase");

				$dbHandle->exec("BEGIN EXCLUSIVE TRANSACTION");

				$result = $dbHandle->query("SELECT count(*) FROM userdatabase.users");
				$users = $result->fetchColumn();
				$result = null;

				$result = $dbHandle->query("SELECT setting_value FROM userdatabase.settings WHERE setting_name='settings_global_default_permissions' LIMIT 1");
				$default_permissions = $result->fetchColumn();
				$result = null;

				if ($users == 0) {
					$permissions = 'A';
				} else {
					!empty($default_permissions) ? $permissions = $default_permissions : $permissions = 'U';
				}

				$user->setPermissions($permissions);
				$rows = 0;

				$quoted_user = $dbHandle->quote($user->getUsername());

				if ($users > 0) {
					$count = $dbHandle->query("SELECT count(*) FROM userdatabase.users WHERE username=$quoted_user LIMIT 1");
					$rows = $count->fetchColumn();
					$count = null;
				}

				if ($rows == 0) {

					$dbHandle->exec("INSERT INTO userdatabase.users (username,password,permissions) VALUES ($quoted_user,'".md5($user->getPassword())."','$permissions')");

					$last_id = $dbHandle->query("SELECT last_insert_rowid() FROM userdatabase.users");
					$id = $last_id->fetchColumn();
					$last_id = null;

					$dbHandle->exec("INSERT INTO projects (userID,project) VALUES ($id,$quoted_user || '''s project')");

					$user = array("userID"=>$user->getId(),"username"=>$user->getUsername(), "password"=>$user->getPassword(), "permissions"=>$user->getPermissions());
			
					$_SESSION['user_id'] = $user['userID'];
					$_SESSION['user'] = $user['username'];
					$_SESSION['password'] = $user['password'];
					$_SESSION['permissions'] = $user['permissions'];
					$_SESSION['auth'] = true;

				} else {
					die ('Username already exists.');
				}

				$dbHandle->exec("COMMIT TRANSACTION");

				if (isset($_SESSION['auth'])) {

					$connection = '';
					$proxy_setting = array();

					$proxy = $dbHandle->query("SELECT setting_name,setting_value FROM settings WHERE setting_name LIKE 'settings_global_%'");

					$proxy_settings = $proxy->fetchAll(PDO::FETCH_ASSOC);

					while(list($key,$proxy_setting) = each($proxy_settings)) {
						if($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'proxy') {
							$connection = 'proxy';
							break;
						}
						if ($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'autodetect') {
							$_SESSION['connection'] = "autodetect";
							break;
						}
						if ($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'url') {
							$_SESSION['connection'] = "url";
						}
						if ($proxy_setting['setting_name'] == 'settings_global_wpad_url') {
							$_SESSION['wpad_url'] = $proxy_setting['setting_value'];
						}
					}

					if ($connection == "proxy") {
						$proxy_setting = array();
						reset($proxy_settings);
						while(list($key,$proxy_setting) = each($proxy_settings)) {
							$setting_name = substr($proxy_setting['setting_name'], 16);
							$_SESSION[$setting_name] = $proxy_setting['setting_value'];
						}
					}

					####### create directory for caching ########

					@mkdir($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id());
				}

				$dbHandle->exec("DETACH DATABASE $quoted_path");
				$dbHandle = null;
		
				die('OK');				
				///////////////end register////////////////////////////////			
			}
						
			$user = array("userID"=>$user->getId(),"username"=>$user->getUsername(), "password"=>$user->getPassword(), "permissions"=>$user->getPermissions());
			
            $_SESSION['user_id'] = $user['userID'];
            $_SESSION['user'] = $user['username'];
            $_SESSION['password'] = $user['password'];
            $_SESSION['permissions'] = $user['permissions'];
            $_SESSION['auth'] = true;
        }

    } else {

        /*IF LDAP NOT ENABLED, CHECK THE LOCAL DB*/
        $result = $dbHandle->query("SELECT userID,permissions FROM userdatabase.users WHERE username=$username_quoted AND password='".md5($_POST["pass"])."' LIMIT 1");
        $user = $result->fetch(PDO::FETCH_ASSOC);
        $result = null;

        if (!empty($user['userID'])) {
            $_SESSION['user_id'] = $user['userID'];
            $_SESSION['user'] = $_POST['user'];
            $_SESSION['password'] = md5($_POST['pass']);
            $_SESSION['permissions'] = $user['permissions'];
            $_SESSION['auth'] = true;
        }
    }

    /*OK, THIS IS A REGISTERED USER. DO THE PROXY SETTINGS AND CREATE A TEMP DIR*/
    if(isset($_SESSION['auth'])) {

        $connection = '';
        $proxy_setting = array();

        $proxy = $dbHandle->query("SELECT setting_name,setting_value FROM settings WHERE setting_name LIKE 'settings_global_%'");

        $proxy_settings = $proxy->fetchAll(PDO::FETCH_ASSOC);

        while(list($key,$proxy_setting) = each($proxy_settings)) {
            if($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'proxy') {
                $connection = 'proxy';
                break;
            }
            if ($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'autodetect') {
                $_SESSION['connection'] = "autodetect";
                break;
            }
            if ($proxy_setting['setting_name'] == 'settings_global_connection' && $proxy_setting['setting_value'] == 'url') {
                $_SESSION['connection'] = "url";
            }
            if ($proxy_setting['setting_name'] == 'settings_global_wpad_url') {
                $_SESSION['wpad_url'] = $proxy_setting['setting_value'];
            }
        }

        if ($connection == "proxy") {
            $proxy_setting = array();
            reset($proxy_settings);
            while(list($key,$proxy_setting) = each($proxy_settings)) {
                $setting_name = substr($proxy_setting['setting_name'], 16);
                $_SESSION[$setting_name] = $proxy_setting['setting_value'];
            }
        }

        $result = $dbHandle->query("SELECT setting_name,setting_value FROM settings WHERE userID=".intval($_SESSION['user_id']));

        while ($custom_settings = $result->fetch(PDO::FETCH_ASSOC)) {

            $_SESSION[substr($custom_settings['setting_name'],9)] = $custom_settings['setting_value'];
        }

        ####### create directory for caching ########

        @mkdir($temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id());

    } else {
        die('Bad username or password.');
    }

    $dbHandle->exec("DETTACH DATABASE $quoted_path");
    $dbHandle = null;

    die('OK');
}
///////////////end authentication/////////////////////////
?>

<table cellspacing="0" class="noprint" style="width:99%;margin-left:4px">
    <tr>
        <td class="topindex" id="bottomrow" width="<?php print (isset($_SESSION['auth'])) ? '60%' : '20%' ?>" style="padding-top:3px;line-height:22px;height:22px">
            <a href="leftindex.php?select=library" title="All Items" class="topindex topindex_clicked ui-corner-all" id="link-library">Library</a>
            <?php
            if (isset($_SESSION['auth'])) {
                ?>
            <a href="leftindex.php?select=shelf" title="Personal Shelf" class="topindex ui-corner-all" id="link-shelf">Shelf</a>
            <a href="leftindex.php?select=desktop" title="Create/Open Projects" class="topindex ui-corner-all" id="link-desk">Desk</a>
            <a href="leftindex.php?select=clipboard" title="Temporary List" class="topindex ui-corner-all" id="link-clipboard">Clipboard</a>
                <?php
                if (isset($_SESSION['permissions']) && ($_SESSION['permissions'] == 'A' || $_SESSION['permissions'] == 'U')) {
                    ?>
            <a href="addarticle.php" class="topindex ui-corner-all" id="link-record">Add Record</a>
                    <?php
                }
                ?>
            <a href="tools.php" class="topindex ui-corner-all" id="link-tools">Tools</a>
            <a href="topindex.php?action=signout" class="topindex ui-corner-all" id="link-signout">Sign Out</a>
                <?php
            }
            ?>
        </td>
        <td width="<?php print (isset($_SESSION['auth'])) ? '40%' : '80%' ?>" class="topindex" style="padding-top:3px;line-height:22px;height:22px;text-align:right">
            <?php
			/////////if not authenticated show the forms////////////
            if (!isset($_SESSION['auth'])) {
                $signin_mode = '';
                $disallow_signup = '';
                database_connect($usersdatabase_path, 'users');
                $all_users = $dbHandle->query("SELECT username FROM users ORDER BY username COLLATE NOCASE");
                $all_users_count = $dbHandle->query("SELECT count(*) FROM users");
                $setting1 = $dbHandle->query("SELECT setting_value FROM settings WHERE setting_name='settings_global_signin_mode' LIMIT 1");
                $setting2 = $dbHandle->query("SELECT setting_value FROM settings WHERE setting_name='settings_global_disallow_signup' LIMIT 1");
                $rows = $all_users_count->fetchColumn();
                $signin_mode = $setting1->fetchColumn();
                $disallow_signup = $setting2->fetchColumn();
                $dbHandle = null;
                ?>
            <form action="topindex.php" method="POST" id="signinform">
                User:
                    <?php
                    if($signin_mode == 'textinput' || $ldap_active) {
                        print '<input type="text" name="user" size="10" value="">';
                    } else {
                        print '<select name="user"><option></option>';
                        while ($user = $all_users->fetch(PDO::FETCH_ASSOC)) {
                            print '<option';
                            if ($rows == 1) print ' selected';
                            print ' value="'.$user['username'].'">'.$user['username'].'</option>';
                        }
                        print '</select>';
                    }
                    ?>
                Password: <input type="password" name="pass" size="10" value="">
                &nbsp;<button id="signinbutton">Sign In</button>
                    <?php
                    if(!$ldap_active && $disallow_signup != '1') print '<span style="cursor:pointer" id="register">Create Account</span>';
                    ?>
            </form>
            <form action="topindex.php" method="POST" id="signupform" style="display: none">
                User: <input type="text" name="user" size="10" value="">
                Password: <input type="password" name="pass" size="10" value="">
                Retype password: <input type="password" name="pass2" size="10" value="">
                &nbsp;<button id="signupbutton">Sign Up</button>
                <span style="cursor:pointer" id="login">Sign In</span>
            </form>
            <div id="errors" style="display:none" title="Error!"></div>
            <?php
			///////////if authenticated, welcome and display change on index page////////
            } else {
                print 'I, Librarian '.$version.' ';
                print '<button id="signedin" style="height:20px;width:20px">Sign Out</button> <span id="username-span">'.$_SESSION['user'].'</span>';
            }
            ?>
        </td>
    </tr>
</table>